﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using WebTest.Infrastructure.Interfaces;

namespace WebTest.Infrastructure.NLog
{
    public class NLogService : INLogService
    {
        private readonly IHttpContextAccessor contextAccessor;
        private readonly ILogger<NLogService> logger;

        public NLogService(IHttpContextAccessor contextAccessor, ILogger<NLogService> logger)
        {
            this.contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public void LogError(Exception ex)
        {
            var host = contextAccessor.HttpContext?.Request?.Host.Host;
            var creator = contextAccessor.HttpContext?.User?.Identity?.Name ?? "system";
            var body = ex.InnerException?.Message ?? ex.Message;
            LogMessage message = new LogMessage(host, creator, body, ex.StackTrace);

            logger.LogError(message.Format());
        }
    }
}
